package com.xry.www;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


public class IMAGE {

    //获得网页上图片列表的地址并储存在txt中
    public void getUrlList(String pagePath, String targetPath) throws IOException {
        URL url = new URL(pagePath);
        URLConnection connection = url.openConnection();
        InputStream inputStream = connection.getInputStream();
        try (FileOutputStream fileOutputStream = new FileOutputStream(targetPath)) {
            int count = -1;
            byte[] data = new byte[1024];
            while ((count = inputStream.read(data)) != -1) {
                fileOutputStream.write(data, 0, count);
            }
        }
    }

    public void imageSort(List<File> images,List<String> imagesort) throws IOException {
        long[] large=new long[5];
        int i=0;
        int j=0;

        images.sort(new Comparator<File>() {
            @Override
            public int compare(File o1, File o2) {
                return Long.compare(o1.length(), o2.length());
            }
        });


        for(File f1:images){
            large[i]=f1.length();
            imagesort.add(large[i]+" "+f1.getPath());
            i++;
        }

        for(String s:imagesort){
            System.out.println(large[j]+"  "+s);
            j++;
        }
    }

    public List<String> getImageList(String imageListPath) throws IOException {
        FileReader fileReader = new FileReader(imageListPath);
        BufferedReader bufferedReader = new BufferedReader(fileReader);
        List<String> imageList = new ArrayList<>();
        String line = null;
        while ((line = bufferedReader.readLine()) != null) {
            imageList.add(line);
        }
        return imageList;
    }

    public void downloadImage(List<String> imagePathList,List<File> images) throws IOException {
        for (String eachImage : imagePathList) {
            //System.out.println("图片列表："+eachImage);
            URL url = new URL(eachImage);
            URLConnection connection = url.openConnection();
            InputStream inputStream = connection.getInputStream();
            String dir=eachImage.substring(7,(eachImage.length())-7);
            //System.out.println(dir);
            File targetdirs=new File("C:\\Users\\谢睿怡\\image\\"+dir);
            //System.out.println(targetdirs);
            targetdirs.mkdirs();
            try (FileOutputStream fileOutputStream = new FileOutputStream("C:\\Users\\谢睿怡\\image\\"+dir+"\\01.jpg")) {
                int count = -1;
                byte[] data = new byte[1024];
                while ((count = inputStream.read(data)) != -1) {
                    fileOutputStream.write(data, 0, count);
                }
                File f=new File("C:\\Users\\谢睿怡\\image\\"+dir+"\\01.jpg");
                images.add(f);
            }
        }
    }
}

